package com.vehicle.repair.controller;

import com.vehicle.repair.model.Repairer;
import com.vehicle.repair.service.RepairerService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/repairers")
public class RepairerController {
    private final RepairerService repairerService;

    public RepairerController(RepairerService repairerService) {
        this.repairerService = repairerService;
    }

    @PostMapping
    public ResponseEntity<Repairer> registerRepairer(@RequestBody Repairer repairer,
                                                    @RequestParam Integer userId) {
        try {
            Repairer registeredRepairer = repairerService.registerRepairer(repairer, userId);
            return ResponseEntity.ok(registeredRepairer);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<Repairer> getRepairerById(@PathVariable Integer id) {
        Optional<Repairer> repairer = repairerService.getRepairerById(id);
        return repairer.map(ResponseEntity::ok)
                      .orElseGet(() -> ResponseEntity.notFound().build());
    }

    @GetMapping("/skill/{skillType}")
    public ResponseEntity<List<Repairer>> getRepairersBySkillType(@PathVariable String skillType) {
        try {
            Repairer.SkillType type = Repairer.SkillType.valueOf(skillType);
            List<Repairer> repairers = repairerService.getRepairersBySkillType(type);
            return ResponseEntity.ok(repairers);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<Repairer> updateRepairer(@PathVariable Integer id,
                                                @RequestBody Repairer repairer) {
        repairer.setRepairerId(id);
        Repairer updatedRepairer = repairerService.updateRepairer(repairer);
        return ResponseEntity.ok(updatedRepairer);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteRepairer(@PathVariable Integer id) {
        repairerService.deleteRepairer(id);
        return ResponseEntity.noContent().build();
    }
}
